#!/bin/bash
### BEGIN INIT INFO
# Provides:          lzx_nas
# Required-Start:    $network $local_fs
# Required-Stop:     $network $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      1
# Short-Description: Start lzx_nas
# Description: Start and Stop the lance_tool
### END INIT INFO
#
# Lance Tool
#
# chkconfig: 345 20 80
# description: Lance Tool
#
# /etc/rc.d/init.d/lance_*
# See how we were called.

LOG_FILE="/var/log/`basename $0`.`hostname`.log"

function time_stamp()
{
  date +%Y%m%d_%H%M%S
}

function log_msg(){
  CONTENT="$1"
  TYPE="$2"

  echo "[$(time_stamp)]: ""$CONTENT" >> $LOG_FILE
  [ "$TYPE" == "print" ] && echo "$CONTENT"
  return 0
}

function get_proc_pid(){
    ps -elf | grep "`basename $0`" | grep background | grep -v grep | awk '{print $4}' | head -n 1
    return
}


function back_up_lvm()
{
  /sbin/vgcfgbackup vg_lance -f /root/config/vg_lance.`time_stamp`.vgcfg
}

function print_smartctl()
{
  ctl_param="$1"
  ctl_info="$2"
  tgt_dev="$3"
  col_cnt="$4"
  AWK="awk"

  [ "$ctl_param" == "" ] && return
  [ "$ctl_param" != "A" ] && AWK="awk -F:"
  echo '<TR align=left>'
  echo '<Th colspan="'$col_cnt'">'$tgt_dev" "$ctl_info' SECTION</th>'
  echo '</TR>'

  smartctl -$ctl_param $tgt_dev | $AWK 'BEGIN{ \
    PRT=0; CNT=0; MAX="'"$col_cnt"'"; \
    MAX=MAX+0;\
  }{\
    if (PRT == 1 && NF >= MAX ) {\
      CNT=CNT+1;\
      if ( (CNT % 2) == 1 ){ CLS="tableBody1"; } else { CLS="tableBody2";}\
      print "<TR align=middle>";\
      for (i = 1; i <= MAX; i++){\
        print "<TD align=left  class=",CLS,">",$i,"</TD>";\
      }
      print "</TR>";\
    }\
    if ( $0 ~ /^===.*===$/) {PRT = 1}\
  }'

  return
}

function print_single_disk()
{
  DEV="$1"
  echo "<br/>"
  echo "<br/>"
  echo "<H1 align=center>$DEV</HT>"
  echo '<TABLE cellPadding="1" cellSpacing="1" class="tableborder1" align="center">'
  print_smartctl i INFORMATION "$DEV" 2
  print_smartctl H HEALTH "$DEV" 2
  echo '</TABLE>'

  echo '<TABLE cellPadding="1" cellSpacing="1" class="tableborder1" align="center">'
  print_smartctl A Attributes "$DEV" 10
  echo '</TABLE>'
}

function print_smartd()
{
  cat $0 | awk 'BEGIN{ PRT=0; }{\
    if ( $0 ~ /^<!DOCTYPE HTML PUBLIC.*/ ) { PRT=1; }\
    if ( PRT == 1 ) { print $0; }\
  }' | \
    grep -v "^<TABLE" |\
    grep -v "^<TR" |\
    grep -v "^<Th" |\
    grep -v "^</TR>" |\
    grep -v "^<TD" |\
    grep -v "^</table>" |\
    grep -v "^</body></html>"
  echo "<H1>Lance NAS SMARTD Status</H1>"
  cat /proc/partitions | grep "sd[a-z]$" | awk '{print $NF}' | while read sd
  do
    print_single_disk /dev/$sd
  done
  echo "</body></html>"
}

function mount_local_iscsi()
{
  cat /proc/partitions > /tmp/t1
  log_msg "Unmount pbfd" print
  umount /pbfd

  log_msg "Starting open-iscsi service ......" print
  /etc/init.d/open-iscsi start 1>>$LOG_FILE 2>&1
  sleep 5
  
  log_msg "/sbin/iscsiadm -m node --logout 1" print
  /sbin/iscsiadm -m node --logout 1>>$LOG_FILE 2>&1
  log_msg "/sbin/iscsiadm -m discovery -t sendtargets -p 192.168.0.121" print
  /sbin/iscsiadm -m discovery -t sendtargets -p 192.168.0.121 1>>$LOG_FILE 2>&1
  log_msg "/sbin/iscsiadm -m node -o show" print
  /sbin/iscsiadm -m node -o show 1>>$LOG_FILE 2>&1
  log_msg "/sbin/iscsiadm -m node --login" print
  /sbin/iscsiadm -m node --login 1>>$LOG_FILE 2>&1
  log_msg "/sbin/iscsiadm -m session -o show" print
  /sbin/iscsiadm -m session -o show 1>>$LOG_FILE 2>&1
  sleep 10

  log_msg "Current Partitions: " print
  cat /proc/partitions 1>>$LOG_FILE 2>&1
  cat /proc/partitions > /tmp/t2

  diff /tmp/t1 /tmp/t2 | \
    awk '( NF>=5 && $4>1000000000 && $5~/^sd[a-z][0-9]$/ ){print $4, $5}' | \
    head -n 1 | \
    while read size sdx
    do
      log_msg "Mounting new added partition [$sdx]...... " print
      /sbin/mount.ntfs /dev/$sdx /pbfd -o ro
    done

  return
}

function is_local_ip()
{
  test_ip="$1"
  ifconfig | grep "inet addr" | awk -F: '{print $2}' | awk '{print $1}' | \
  while read local_ip
  do
    [ "$test_ip" == "$local_ip" ] && echo "true" && return
  done
  echo "false"
  return
}

function get_active_lan()
{
  for ip_p4 in $(seq 120 125)
  do
    test_ip="192.168.0.$ip_p4"
    if [ "$(is_local_ip $test_ip)" == "false" ]
    then
      link_test=$(ping -c 3 "$test_ip" | grep "time=")
      if [ "$link_test" != "" ]
      then
        echo "$test_ip"
      fi
    fi
  done
}

function auto_shutdown()
{
  if [ "`get_active_lan`" == "" ]
  then
    log_msg "Can not find active lan pc, maybe not started by lan, quit!" print
    return
  fi

  death_counter=3
  log_msg "death_counter actived, $death_counter times all server offline will leads to NAS automaticlly shutdown." print
  while [ "1" == "1" ]
  do
    sleep 120 # Every 2 minutes

    if [ "`get_active_lan`" == "" ]
    then
      let death_counter=death_counter-1
      log_msg "death_counter=$death_counter" print
    else
      let death_counter=3
    fi

    if [ $death_counter -le 0 ]
    then
      log_msg "death_counter=$death_counter, shutdown now!" print
      init 0
      exit 0
    fi
  done

  return
}

case "$1" in
    start)
        log_msg "Starting `basename $0` ......" print
        nohup $0 background 1>/dev/null 2>&1 &
        exit 0
    ;;

    stop)
        PID=`get_proc_pid`
        if [ "$PID" != "" ]
        then
            kill -s 9 $PID
            log_msg "Stopped `basename $0` [$PID]" print
        fi
        exit 0
    ;;

    restart)
        $0 stop
        $0 start
        exit 0
    ;;

    test)
        echo "Just a test ......"
        print_smartd >/var/www/index.html
        exit 0
    ;;

    status)
        echo "Status of `basename $0`:"
        exit 0
    ;;

    background)
        log_msg "Wait 30 secs for server ready ......" print
        sleep 30
        back_up_lvm
        print_smartd >/var/www/index.html
        mount_local_iscsi

        log_msg "Start auto-shutdown deamon ......" print
        auto_shutdown

        exit 0
    ;;

    *)
        echo "Usage: /etc/init.d/`basename $0` {start|stop|restart|status}"
        exit 1
    ;;
esac


exit 0

# Ok, the following is SMARTD HTML template
# I hate to write it to another file
# So just paste it here

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<meta name="description" content="Nothing">
<title>Lance NAS SMARTD monitor</title>
<style type=text/css>
A:link,A:active,A:visited{TEXT-DECORATION:none ;Color:#000000}A:hover{TEXT-DECORATION: underline;Color:#4455aa}
BODY{FONT-SIZE: 12px;COLOR: #000000;FONT-FAMILY:  ..;
scrollbar-face-color: #DEE3E7;scrollbar-highlight-color: #FFFFFF;scrollbar-shadow-color: #DEE3E7;scrollbar-3dlight-color: #D1D7DC;scrollbar-arrow-color:  #006699;scrollbar-track-color: #EFEFEF;scrollbar-darkshadow-color: #98AAB1;}
font{line-height : normal ;}
TD{font-family: ..;font-size: 12px;line-height : 15px ;}
th{background-color: #000000;color: white;font-size: 12px;font-weight:bold;}
td.TableTitle2{background-color: ##E4E8EF;}
td.TableBody1{background-color: #F7F7F7;line-height : normal ;}
td.TableBody2{background-color: #EAEAEA;line-height : normal ;}
td.TopDarkNav{background-image: url(Skins/Default/css/default/topbg.gif);}
td.TopLighNav{background-image: url(Skins/Default/css/default/bottombg.gif);}
td.TopLighNav1{background-image: url(Skins/Default/css/default/tabs_m_tile.gif);}
td.TopLighNav2{background-color:#FFFFFF}
.tableBorder1{width:98%;border: 1px; background-color: #B0B0B0;}
.tableBorder2{width:98%;border: 1px #DEDEDE solid; background-color: #EFEFEF;}
#TableTitleLink A:link, #TableTitleLink A:visited, #TableTitleLink A:active {COLOR: #FFFFFF;    TEXT-DECORATION: none;}#TableTitleLink A:hover {COLOR: #FFFFFF;TEXT-DECORATION: underline;}
input,select,Textarea,option{font-family:Tahoma,Verdana,".."; font-size: 12px; line-height: 15px;COLOR: #000000;}
.normalTextSmall {     font-size : 11px;    color : #000000;     font-family: Verdana, Arial, Helvetica, sans-serif;}
.menuskin {
        BORDER: #666666 1px solid; VISIBILITY: hidden; FONT: 12px Verdana;
        POSITION: absolute;
        BACKGROUND-COLOR:#EFEFEF;
        background-image:url("Skins/Default/dvmenubg3.gif");
        background-repeat : repeat-y;
        }
.menuskin A {
        PADDING-RIGHT: 10px; PADDING-LEFT: 25px; COLOR: black; TEXT-DECORATION: none; behavior:url(inc/noline.htc);
        }
#mouseoverstyle {
        BACKGROUND-COLOR: #C9D5E7; margin:2px; padding:0px; border:#597DB5 1px solid;
        }
#mouseoverstyle A {
        COLOR: black
}
.menuitems{
        margin:2px;padding:1px;word-break:keep-all;
}

a.navlink:link {color: #000000; text-decoration:none}
a.navlink:visited {color: #000000; text-decoration:none }
a.navlink:hover {color: #003399; text-decoration:none }
.BrightClass{background-color: #D7D7D7; }
div.quote{margin:5px 20px;border:1px solid #CCCCCC;padding:5px;background:#F3F3F3 ;line-height : normal ;
}
div.HtmlCode{margin:5px 20px;border:1px solid #CCCCCC;padding:5px; background:#FDFDDF ;
font-size:14px;font-family:Tahoma;font-style : oblique;line-height : normal ;font-weight:bold;
}
</style>
</head>

<body topmargin="0" leftmargin="0">
<TABLE cellPadding="1" cellSpacing="1" class="tableborder1" align="center">
<TR align=middle>
<Th height="25" width="32" id="tabletitlelink"><a href="list.asp?boardid=1&page=262&action=batch">..</a></th>
<Th width=*>. .  (.<img src="Skins/Default/plus.gif">........)</Th>
<Th width="80">. .</Th>
<Th width="40">..</th>
<Th width="40">..</Th>
<Th width="195">....</th>
</TR>
<TR align=middle>
<TD align=middle  class=tableBody2 height="21" >..</td>
<TD class=tableBody2 align="left" width=* align=middle>&nbsp;&nbsp;<a href="dispbbs.asp?BoardID=1&ID=2367773&page=262">...........</a></TD>
<TD class=tableBody2 width="80" align=middle><a href="dispuser.asp?id=217613" target=_blank>freeman64</a></TD>
<TD class=tableBody2 width="40" align=middle >0</TD>
<TD class=tableBody2 width="40" align=middle>186</TD>
<TD class=tableBody2 width="195" align=middle>2013-3-21 18:42:53</TD>
</TR>
</table>
</body></html>

